package com.beilang.base.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;


public final class SortUtil {
	protected transient static Logger log = Logger.getLogger(PropertyComparator.class);
	public static List distinct(List oList,String propName )
	throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
	{
		 List oResult=new ArrayList();
	   	 Set oSet = new HashSet();
		 for( int i=0;i<oList.size();i++)
		 {
			 Object oObj = oList.get(i);
			 Object oKey = PropertyUtils.getProperty(oObj, propName);
			 if( oKey!=null&&!oSet.contains(oKey) )
			 {
				 oSet.add(oObj);
			 }
		 }
		 oResult.addAll(oSet);
		 oSet.clear();
		return oResult;
	}
	public static void sort(List oList,String propName )
	{
		Collections.sort(oList, new PropertyComparator(propName));
	}

	public static void sort(List oList,String propName,boolean isAscending )
	{
		Collections.sort(oList, new PropertyComparator(propName,isAscending));
	}

	public static void sort(Object[] oArray,String propName )
	{
		Arrays.sort(oArray, new PropertyComparator(propName));
	}

	public static void print(List oList,String propName )
	{
		try {
			for(int i=0;oList!=null&&i<oList.size();i++)
			{
				log.debug(PropertyUtils.getProperty(oList.get(i), propName));
			}
		} catch (Exception e) {
                log.error(e.getMessage(), e);
		}
	}




	private static class PropertyComparator implements Comparator
	{
		private String property;
		private boolean isAscending;
		public PropertyComparator(String propName)
		{
			this.property = propName;
			isAscending=true;
		}
		public PropertyComparator(String propName, boolean isAscending)
		{
			this.property = propName;
			this.isAscending=isAscending;
		}
	   /**
	    * Compare the property of two Objects. Callback for sort.
	    */
	   public final int compare ( Object a, Object b )
	   {
		   int result =0;
		   try{
			   Object aProp= PropertyUtils.getProperty(a, property);
			   Object bProp = PropertyUtils.getProperty(b, property);
			   if( aProp!=null&&bProp!=null )
				   result=( (Comparable)aProp ).compareTo( (Comparable)bProp );
			   else if(aProp==null&&bProp==null){
				   result=0;
			   }else{
				   result= aProp!=null?1:-1;
			   }
		   }catch(Exception e)
		   {
			   log.error("error in PropertyComparator for "+property,e);
		   }
		   return result*(isAscending?1:-1);
	   }
	}
}

